﻿<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/view/common/taglibs.jsp"%>

<!DOCTYPE>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="renderer" content="webkit|ie-comp|ie-stand">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
	<meta http-equiv="Cache-Control" content="no-siteapp" />
	<title>用户列表</title>
	<style>
		/** 表格的操作按钮的内边距 */
		.btn{
			padding: 1px 8px!important;
			font-size: 12px!important;
		}
		/**顶部操作按钮的内边距*/
		.border .btn {
			display: inline-block;
			padding: 5px 12px!important;
			margin-bottom: 0;
			font-weight: 400;
			line-height:18px;
			text-align: center;
			white-space: nowrap;
			vertical-align: middle;
			cursor: pointer;
			user-select: none;
			background-image: none;
			border: 1px solid transparent;
			border-radius: 4px;
			margin-left: 10px;
		}
		.label {
			display: inline!important;
			padding: .2em .6em .3em!important;
			font-size: 11px!important;
			font-weight: 700!important;
			line-height:20px!important;
			height: 20px!important;
			color: #fff!important;
			text-align: center!important;
			white-space: nowrap!important;
			vertical-align: baseline!important;
			border-radius: .25em!important;
		}
		/**表格tr背景色*/
		.table thead tr{
			background-color: #fff!important;
		}
		/**表格单元格样式*/
		.table thead tr th{
			padding: 10px;
		}
		/**表格单元格border*/
		.table tbody tr td{border: 0px!important;border-bottom: 1px solid #e7eaec !important;border-left: 1px solid #e7eaec !important;}
		.table-bordered > thead > tr > th, .table-bordered > thead > tr > td{border-bottom-width: 1px!important;}
		.table-bordered{border: 0px!important;}
		/**表头的高度*/
		.table thead > tr > th,.table thead > tr > td{padding: 8px!important;}
	</style>
	<!-- 静态css、js资源 -->
	<%@ include file="/WEB-INF/view/common/common.jsp"%>
	<script src="${_cdnStaticResourcesPath}/resources/static/js/jquery-fixed.js" type="text/javascript" ></script>
</head>

<body id="applist_frame_box">
<div class="page-content clearfix">
	<div id="user_list_style">
		<!--条件查询-->
		<div class="search_style" style="background-color: #fff;">
			<div class="title_names">搜索查询</div>
			<ul class="search_content clearfix">
				<li><label class="l_f">用户姓名</label><input id="realName" name="realName" type="text"  class="text_add ml-10" placeholder="请输入用户姓名"  style="width:200px;height: 30px;line-height: 30px;"/></li>
				<li class="ml-10">
					<label class="l_f">账户状态</label>
					<div class="col-xs-6">
						<span class="select-box">
							<select class="select ml-10" id="status" name="status" style="height: 30px;line-height: 30px;">
								<option value="">全部</option>
								<c:forEach items="${status}" var="s">
									<option value="${s}">${s.description}</option>
								</c:forEach>
							</select>
						</span>
					</div>
				</li>
				<li class="ml-10">
					<label class="l_f">所属应用</label>
					<div class="col-xs-4">
						<span class="select-box">
							<select class="select ml-10" id="appId" name="appId" style="height: 30px;line-height: 30px;">
								<option value="">全部</option>
								<c:forEach items="${apps}" var="app">
									<option value="${app.id}">${app.name}</option>
								</c:forEach>
							</select>
						</span>
					</div>
				</li>
				<li style="width:90px;margin-left: 20px;"><button type="button" class="btn_search" style="height: 30px;line-height: 30px;"><i class="icon-search"></i>查询</button></li>
			</ul>
		</div>

		<!--功能按钮-->
		<div class="border clearfix">
			<span class="l_f">
				<a style="background-color: #fff!important;border-color: #ccc!important;color:#333!important;text-shadow: none!important;" href="javascript:void(0);" onfocus="this.blur();" title="刷新用户列表" onclick="reloadTable(true);" class="btn btn-default"><i class="icon-refresh"></i>刷新列表</a>
				<a href="${ctx}/user/toAddView" title="添加用户" class="btn btn-success Order_form"><i class="icon-plus"></i>添加用户</a>
				<a href="javascript:void(0)" class="btn btn-danger" onclick="batchDeleteUser();"><i class="icon-trash"></i>批量删除</a>
				<a style="background-color: #1AAAAA!important;border-color: #1AAAAA!important;" href="javascript:void(0);" class="btn btn-danger" onclick="settingUserRole();"><i class="icon-legal"></i>分配角色</a>
			</span>
		</div>

		<!--内容-->
		<div class="h_products_list clearfix" id="table_list">
			<!--左侧菜单 —— 应用列表-->
			<div id="scrollsidebar" class="left_Treeview">
				<div class="show_btn" id="rightArrow"><span></span></div>
				<div class="widget-box side_content" >
					<div class="side_title"><a title="隐藏" class="close_btn"><span></span></a></div>
					<div class="side_list"><div class="widget-header header-color-green2"><span style="font-size: 13px;">应用列表(点击查询对应的用户)</span></div>
						<div class="widget-body">
							<div class="widget-main padding-8"><div id="appTree" class="ztree"></div></div>
						</div>
					</div>
				</div>
			</div>

			<!--表格数据-->
			<div class="table_menu_list" id="userListIframe">
				<table class="table table-striped table-bordered table-hover" id="userListTable" style="width: 100%;">
					<thead>
					<tr>
						<th><label><input type="checkbox" class="ace" id="selectAll"/><span class="lbl"></span></label></th>
						<th>用户名</th>
						<th>真实姓名</th>
						<th>角色名称</th>
						<th>系统来源</th>
						<th>账户状态</th>
						<th>创建时间</th>
						<th>更新时间</th>
						<th>操作</th>
					</tr>
					</thead>
					<tbody></tbody>
				</table>
			</div>
		</div>
	</div>
</div>

<input type="hidden" des="获取用户列表url" id="getUserListUrl" value="${ctx}/user/list"/>
<input type="hidden" des="编辑用户url" name="toEditUserUrl" id="toEditUserUrl" value="${ctx}/user/toEditView" />
<input type="hidden" des="删除用户url" name="deleteUserUrl" id="deleteUserUrl" value="<c:url value="/user/deleteUser"/>" />
<input type="hidden" des="批量删除用户url" name="deleteUsersUrl" id="deleteUsersUrl" value="<c:url value="/user/deleteUsers"/>" />
<input type="hidden" des="为用户分配应用url" name="toUserAssignAppUrl" id="toUserAssignAppUrl" value="<c:url value="/user/toUserAssignAppView"/>" />
<input type="hidden" des="为用户分配角色url" name="toUserAssignRoleUrl" id="toUserAssignRoleUrl" value="<c:url value="/user/toUserAssignRoleView"/>" />
<input type="hidden" des="获取应用列表url" name="getAllAppsUrl" id="getAllAppsUrl" value="<c:url value="/app/apps/tree"/>" />
<input type="hidden" name="allApps" value='' des="应用列表json字符串，这里value必须是单引号，避免与allApps值中的双引号冲突，出现问题"/>
</body>
</html>
<script>
    var userListTable;//jquery table全局表格对象
    $(function() {
        userListTable = $('#userListTable').dataTable({
            order: [],  //取消默认排序查询,否则复选框一列会出现小箭头
            dom: '<"top">t<"float_left_l"l><"float_left_i"i><"float_left_r"r>p<"clear">',//设置表格的排版规则(提示语、分页、搜索、页数分组等的位置设置)
            language:lang,//自定义分页的相关信息，用于替换插件默认的配置。详细配置在common.jsp中
            aLengthMenu: [15,10,20,50,100],
            destroy : true,
            bSort : true,
            autoWidth: false,  //自动调整列宽
            processing: false,  //取消插件默认的加载提示
            serverSide: true,  //服务器端分页
            bStateSave: true,//状态保存
            deferRender : true,//控制表格的延迟渲染，可以提高初始化的速度。
            ajax: function (data, callback, settings) {
                var param = {};
                //封装请求参数
                param.draw = data.draw;
                param.start = data.start;//开始的记录序号
                param.page = (data.start / data.length)+1;//当前页码
                param.limit = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                param.realName = $("#realName").val();
                param.status = $("#status").val();
                param.appId = $("#appId").val();
                //设置排序参数
                if(data.order.length > 0){
                    param.order = data.order[0].dir;//排序方式
                    param.sort = data.columns[data.order[0].column].name;//排序字段名
                }
                //ajax请求数据
                $.ajax({
                    type: "POST",
                    url: $("#getUserListUrl").val(),
                    cache: false,  //禁用缓存
                    data: param,  //传入组装的参数
                    dataType: "json",
                    timeout:10000,
                    beforeSend: function(){//请求之前显示loading效果
                        $(".dataTable tr:gt(0)").remove();
                        $(".dataTable thead").append("<tr style='line-height:38px;'><td style='text-align:center;background-color:#FFFFFF;' colspan='9'></td></tr>");
                        $(".dataTable tr:eq(1) td").html("<img src='" + $("#cdnStaticResourcesPath").val() + "/resources/static/images/loading.gif'/><span style='margin-left:5px;vertical-align:middle;'>" + lang.sProcessing + "</span>");
                    },
                    success: function (result) {
                        $(".dataTable tr:gt(0)").remove();//移除loading
                        //封装返回数据
                        var returnData = {};
                        returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                        returnData.recordsTotal = result.recordsTotal;//返回数据全部记录
                        returnData.recordsFiltered = result.recordsFiltered;//后台不实现过滤功能，每次查询均视作全部结果
                        returnData.data = result.data;//返回的数据列表
                        callback(returnData);
                    },
                    error:function(jqXHR, textStatus, errorThrown){
                        $(".dataTable tr:gt(0)").remove();//移除loading
                        $(".dataTable thead").append("<tr style='line-height:38px;'><td style='text-align:center;' colspan='9'></td></tr>");
                        if(textStatus=="timeout"){
                            $(".dataTable tr:eq(1) td").html("<span style='margin-left:5px;vertical-align:middle;color:red;'>数据请求超时，稍后请刷新重试</span>");
                        }else{
                            $(".dataTable tr:eq(1) td").html("<span style='margin-left:5px;vertical-align:middle;color:red;'>数据请求异常，稍后请刷新重试</span>");
                        }
                    },
                });
            },


            //列表表头字段 //visible:是否显示该列，bSortable：是否排序
            //这里的name属性有特别的作用，用于映射数据库对应的字段名。
            //      比如statusName为枚举的值，但数据库对应的字段为status，所以上面在设置请求排序参数的时候，应该获取的是name值，而不是data属性值。
            columns: [
                { "data": "userId" , "bSortable": false ,width : "5%"},
                { "data": "userName" , "bSortable": false, width : "10%"},
                { "data": "realName" , "bSortable": false , "visible": true, width : "10%"},
                { "data": "roleName" , "bSortable": false, width : "10%"},
                { "data": "fromSystem" , "bSortable": false, width : "12%"},
                { "data": "statusName" , name : "status", width : "8%"},
                { "data": "createTime" , name : "createTime", width : "15%"},
                { "data": "updateTime" , name : "updateTime", width : "15%"}
            ],

            //targets：表示具体需要操作的目标列，下标从0开始
            //data: 表示我们需要的某一列数据对应的属性名
            //render:返回需要显示的内容。在此我们可以修改列中样式，增加具体内容
            "columnDefs": [
                {
                    "targets": [0],
                    "data": "userId",
                    "render": function(data, type, full) {
                        var str = "";
                        if(full.userName == 'admin'){
                            str = "disabled='disabled'";
                        }
                        return '<label><input ' + str + ' type="checkbox" class="ace" value="' + data + '" id="user_chbox_' + data + '"/><span class="lbl"></span></label>';
                    }
                },
                {
                    "targets": [1],
                    "data": "userName",
                    "render": function(data, type, full) {
                        if(full.userName == 'admin'){
                            return data;
                        }else{
                            return "<a style='text-decoration: underline;color:#0A81E5;' onClick=\"userEdit('编辑用户信息','" + $("#toEditUserUrl").val() + "?userId=" + full.userId + "','','35%','45%')\" href=\"javascript:;\">" + data + "</a>";
						}
                    }
                },
                {
                    "targets": [5],
                    "data": "status",
                    "render": function(data, type, full) {
                        if(full.status == "ENABLE"){
                            return "<span style='background-color: #52AD52!important;' class=\"label label-success radius\">" + full.statusName + "</span>";
                        }else if(full.status == "DISABLE"){
                            return "<span class=\"label label-danger radius\">" + full.statusName + "</span>";
                        }else if(full.status == "LOCK"){
                            return "<span class=\"label label-warning radius\">" + full.statusName + "</span>";
                        }
                        return data + "";
                    }
                },
                {
                    "targets": [8],
                    "data": "userId",
                    "render": function(data, type, full) {
                        var str = "";
                        if(full.userName == 'admin'){
                            str = "disabled='disabled'";
						}
                        return "<a " + str + " style=\"background-color: #428BCA!important;border-color: #428BCA!important;\" title=\"编辑用户信息\" onclick=\"userEdit('编辑用户信息','" + $("#toEditUserUrl").val() + "?userId=" + data + "','','35%','45%')\" href=\"javascript:;\" class=\"btn btn-xs btn-info\"><i class=\"icon-edit bigger-120\"></i></a>"
							+  "<a " + str + " style=\"background-color: #1AAAAA!important;border-color: #1AAAAA!important;\" title=\"分配角色\" onclick=\"settingUserRoleOk('" + data + "')\" href=\"javascript:;\" class=\"btn btn-xs\"><i class=\"icon-legal\"></i></a>"
                            +  "<a " + str + " title=\"删除用户\" onclick=\"userDelete('" + data + "')\" href=\"javascript:;\" class=\"btn btn-xs btn-danger\"><i class=\"icon-trash bigger-120\"></i></a>";
                    }
                }
            ],

            //创建行的回调。行背景颜色处理
            createdRow : function(row, data, dataIndex){
                $(row).children('td').attr('style', 'text-align: center;');//设置表格列居中显示
                //$(row).unbind("mouseenter").unbind("mouseleave");
                if(data.status == "DISABLE"){
                    $(row).children('td').addClass("tr_disable_color");
                }else if(data.status == "LOCK"){
                    $(row).children('td').addClass("tr_lock_color");
                }
            },

            //表格初始化完毕的回调
            initComplete: function(oSettings, json) {}
        }).api();


        //条件查询
        $(".btn_search").click(function (){
            //如果选择了所属应用，则动态更新选中左侧的tree的对应的应用节点
			var appId = $("#appId").val();
            var treeObj = $.fn.zTree.getZTreeObj("appTree");
            treeObj.checkAllNodes(false);//取消所有选中的node
			if(appId != ""){
                var selIndex = $("option:selected", "#appId").index() - 1;
                var treeNode = treeObj.getNodes()[selIndex];//设置节点选中
                treeNode.checked = true;
                treeObj.updateNode(treeNode);//更新节点信息，否则不会生效
			}
            getAllApps();//获取应用tree

			//渲染表格数据
            userListTable.draw();
        });

        //复选框选中事件处理
        $('table th input:checkbox').on('click' , function(){
            var that = this;
            $(this).closest('table').find('tr > td:first-child input:checkbox').each(function(){
                this.checked = that.checked;
                $(this).closest('tr').toggleClass('selected');
            });
        });
        //复选框选中事件处理。(全选复选框事件无须写代码，yui框架已经自动处理事件)
        $('#userListTable tbody').on('change', 'input[type="checkbox"]', function(){
            //如果取消选中，则设置全选为非选中状态
            if(!this.checked){
                var el = $('#selectAll').get(0);
                if(el && el.checked){
                    el.checked = false;
                }
            }else{//选中复选框，判断是否全部选择，设置全选复选框状态
                var checkAll = $("#userListTable tbody input[type='checkbox']");//获取当前页所有复选框
                var checkSel = $("#userListTable tbody input[type='checkbox']:checked");//获取当前页选中的复选框
                if(checkAll.length == checkSel.length){
                    $('#selectAll').prop("checked",true);
                }else{
                    $('#selectAll').prop("checked",false);
                }
            }
        });
    });

    /** ==========================================其他相关功能处理======================================= */
    $(function () {
        //滚动条美化
        $("#userListIframe").niceScroll({
            cursorcolor:"#888888",
            cursoropacitymax:1,
            touchbehavior:false,
            cursorwidth:"5px",
            cursorborder:"0",
            cursorborderradius:"5px"
        });

        //当前页面左侧菜单收缩功能
        $("#user_list_style").fix({
            float : 'left',
            //minStatue : true,
            skin : 'green',
            durationTime :false,
            spacingw:30,//设置隐藏时的距离
            spacingh:260,//设置显示时间距
        });
    });
</script>

<script type="text/javascript">
    //初始化宽度、高度
    $(".widget-box").height(document.body.clientHeight-$(".widget-box").offset().top);
    $(".table_menu_list").height(document.body.clientHeight-$(".widget-box").offset().top);
    //当窗口发生改变是触发
    $(window).resize(function(){
        $(".widget-box").height(document.body.clientHeight-$(".widget-box").offset().top);
        $(".table_menu_list").height(document.body.clientHeight-$(".widget-box").offset().top).css("width","auto").css("position","absolute").css("right",0).css("left",0);
    });
    //变相的设置表格宽度自适应。这里延迟一些毫秒再设置比较有效，如果直接在onload等设置的话有问题，找不到问题在哪里。
    setTimeout(function () {
        $(".table_menu_list").height($(window).height()-$(".widget-box").offset().top).css("width","auto").css("position","absolute").css("right",0).css("left",0);
    },100);


    $(document).ready(function(){
        getAllApps();
    });

    /**
	 * 加载应用tree
	 */
    function loadTree(){
        var setting = {
            check : {
                enable : true //显示check复选框
            },
            view: {
                fontCss : {background:"#FFFFFF"}
            },
            callback : {
                onClick : function(event, treeId, treeNode){
                    treeNodeCallback(event, treeId, treeNode,true);
                },
                onCheck: function(event, treeId, treeNode){
                    treeNodeCallback(event, treeId, treeNode,treeNode.checked);
                }
            }
        };
        var apps = $("input[name='allApps']").val();
        $.fn.zTree.init($("#appTree"), setting, eval("(" + apps + ")"));
	}
    /**
	 * 获取应用列表tree数据
	 */
    function getAllApps(){
        $.ajax({
            type : "post",
            url : $("#getAllAppsUrl").val(),
            dataType : "json",
            data : {
                "showTopParent" : false,
				"open" : false,
                "enable" : true //是否只互殴去可用状态的应用
            },
            success : function(result) {
				$("input[name='allApps']").val(result);
				loadTree();//加载tree
            }
        });
	}
    /**
     * 重新加载表格数据
     * @param clearParmas 是否清空查询参数
     */
    function reloadTable(clearParmas) {
        if(clearParmas){
            $("#appId").val("");
        }
        $(".btn_search").click();
    }

    /**
	 * 左侧应用菜单点击事件
	 */
    function treeNodeCallback(event, treeId, treeNode, isSelected){
        var zTree = $.fn.zTree.getZTreeObj("appTree");
        zTree.checkAllNodes(false);//取消所有选中的node
        if(isSelected){
            treeNode.checked = true;//设置当前点击的node节点为选中状态
            zTree.updateNode(treeNode);//更新节点信息，否则不会生效
            $("#appId").val(treeNode.id);//赋予appId的参数值
		}else{
            $("#appId").val("");
		}
        userListTable.draw();//重新加载table数据
	}

	/*用户-编辑*/
    function userEdit(title,url,id,w,h){
        var loadUniqe;
        zeroModal.show({
            title: title,
            iframe: true,
            url: url,
            opacity: 0.8,
            width: w,
            height: h,
            top: '15%',
            buttons: [{
                className: 'zeromodal-btn zeromodal-btn-primary',
                name: '保存',
                fn: function(opt) {
                    loadUniqe = zeroModal.loading();//loading加载
                    $("#zeromodalIframe").contents().find("#btn_submit").click();//用户编辑页面中的form提交按钮
                    zeroModal.close(loadUniqe); // 关闭loading加载
                    return false;//需要加上return false，防止弹出框自动关闭，不然提交成功等提示信息将不会显示
                }
            }, {
                className: 'zeromodal-btn zeromodal-btn-default',
                name: '取消',
                fn: function(opt) {
                    zeroModal.close(loadUniqe); // 关闭等待框
                }
            }]
        });
    }

	/*用户-删除*/
    function userDelete(userId){
        $("body").dialog({
            type: "danger",
            title: "系统提示",
            discription: '确定要删除该用户吗？',
            animateIn: "fadeInRight-hastrans",//rotateInUpLeft-hastrans
            animateOut: "rotateOutUpLeft-hastrans",
            showBoxShadow:true,
            buttons: [{name: '确定',className: 'defalut'}, {name: '取消', className: 'reverse'}]
        },function(ret) {
            if(ret.index===0){
				$.ajax({
					type : "post",
					url : $("#deleteUserUrl").val(),
					dataType : "json",
					data : {
						"userId" : userId
					},
					success : function(result) {
						if (result.code == 200) {
							$.message("删除成功");
							userListTable.draw();//重新加载table数据
						} else {
							$.message({
								message:result.msg,
								type:'error'
							});
						}
					}
				});
            }else{
                return false;
            }
        });
    }


    //批量删除用户
    function batchDeleteUser(){
        var checks = $("#userListTable tbody input[type='checkbox']:checked");//获取当前页所有复选框
        var userIdStr = "";
        for(var i = 0; i < checks.length; i++){
            var uid = $(checks[i]).val();
            userIdStr += uid;
            if(i < checks.length - 1){
                userIdStr += ",";
            }
        }
        if(userIdStr == ""){
            $.message({
                message:"请先选择用户",
                type:'info'
            });
            return;
        }

        $("body").dialog({
            type: "danger",
            title: "系统提示",
            discription: "确定要删除选中的用户吗？",
            animateIn: "fadeInRight-hastrans",//rotateInUpLeft-hastrans
            animateOut: "rotateOutUpLeft-hastrans",
            showBoxShadow:true,
            buttons: [{name: '确定',className: 'defalut'}, {name: '取消', className: 'reverse'}]
        },function(ret) {
            if(ret.index===0){
				$.ajax({
					type : "post",
					url : $("#deleteUsersUrl").val(),
					dataType : "json",
					data : {
						"userIdArr" : userIdStr
					},
					success : function(result) {
						if (result.code == 200) {
							$.message("删除成功");
							userListTable.draw();//重新加载table数据
						} else {
							$.message({
								message:result.msg,
								type:'error'
							});
						}
					}
				});

            }else{
                return false;
            }
        });
    }

    /**
	 * 分配用户角色
     */
    function settingUserRole() {
        var checks = $("#userListTable tbody input[type='checkbox']:checked");//获取当前页所有复选框
        if(checks.length <= 0){
            $.message({
                message:"请选择一个用户",
                type:'warning'
            });
            return false;
        }
        if(checks.length > 1){
            $.message({
                message:"只能选择一个用户",
                type:'warning'
            });
            return false;
        }
        if($(checks[0]).val() == 1){
            $.message({
                message:"您不能为管理员设置角色",
                type:'warning'
            });
            return false;
		}
        settingUserRoleOk($(checks[0]).val());
    }
    function settingUserRoleOk(userId) {
		window.location.href = $("#toUserAssignRoleUrl").val() + "?userId=" + userId;
    }
</script>